<template>
  <el-form-item :rules="parsedRules"
    :prop="(parentId == null || rowIndex == null) ? config.id : `${parentId}.${rowIndex}.${config.id}`"
    :label="config.attributes.showLabel ? config.attributes.label : ''" v-show="!config.attributes.hidden"
    :label-width="config.attributes.labelWidth ? config.attributes.labelWidth : formConfig.labelWidth"
    :label-position="config.attributes.labelPosition ? config.attributes.labelPosition : formConfig.labelPosition">
    <slot></slot>
  </el-form-item>
</template>

<script setup>
import { inject, watch, ref } from 'vue'

const formConfig = inject('formConfig')

// 定义 props
const props = defineProps({
  config: {
    type: Object,
    required: true,
    default: () => ({ children: [] }),
  },
  rowIndex: {
    type: Number,
    default: null
  },
  parentId: {
    type: String,
    default: null
  }
});

const parsedRules = ref({})

watch(
  () => props.config.rules,
  (newRules) => {
    const parsed = newRules.map(rule => {
      const newRule = { ...rule }
      if (typeof rule.pattern === 'string') {
        try {
          const match = rule.pattern.match(/^\/(.+)\/([gimsuy]*)$/)
          if (match) {
            newRule.pattern = new RegExp(match[1], match[2])
          }
        } catch (e) {
          console.warn(`正则解析失败：${rule.pattern}`, e)
        }
      }
      return newRule
    })
    // 存储解析后的规则，避免污染原始数据
    parsedRules.value = parsed
  },
  { deep: true, immediate: true }
)
</script>

<style scoped></style>